package com.bigdata.demo.service.kg;

import org.neo4j.driver.v1.*;
import org.neo4j.driver.v1.types.Node;
import org.neo4j.driver.v1.types.Path;
import org.neo4j.driver.v1.types.Relationship;
import org.springframework.stereotype.Service;

import java.util.*;
@Service
public class KGServiceImpl implements KGService {
    public static Driver driver;

    static
    {
        driver = GraphDatabase.driver("bolt://127.0.0.1:7687", AuthTokens.basic("neo4j", "123456"));
    }

    @Override
    public String searchByKKS(String kks) {

        Session session = driver.session();

        StatementResult result = session.run(
                "match p=(n:KKS)-[*..4]-(b) where n.CR_EQUIPMENT='"+kks+"' return p limit 25");

        StringBuffer nodes = new StringBuffer();
        StringBuffer links = new StringBuffer();
        nodes.append("\"nodes\":[");
        links.append("\"links\":[");

        while (result.hasNext())
        {
            Record record = result.next();
            List<Value> list = record.values();
            for(Value v : list)
            {
                Path p = v.asPath();
                for(Node n:p.nodes())
                {
                    nodes.append("{");
                    int num = 0;
                    for(String k:n.keys())
                    {
                        nodes.append("\""+k+"\":"+n.get(k)+",");
                        num ++ ;
                        if(num == n.size())
                        {
                            nodes.append("\"id\":"+n.id());
                        }
                    }
                    nodes.append("},");
                }
                nodes=new StringBuffer(nodes.toString().substring(0,nodes.toString().length()-1));
                for(Relationship r:p.relationships())
                {
                    links.append("{");
                    links.append("\"source\":"+r.startNodeId()+","+"\"target\":"+r.endNodeId());
                    links.append(",\"type\":\""+r.type()+"\"");
                    links.append("},");
                }
                links=new StringBuffer(links.toString().substring(0,links.toString().length()-1));

            }
            nodes.append(",");
            links.append(",");

        }
        nodes=new StringBuffer(nodes.toString().substring(0,nodes.toString().length()-1));
        links=new StringBuffer(links.toString().substring(0,links.toString().length()-1));
        nodes.append("]");
        links.append("]");
        String resultJson = "{"+nodes+","+links+"}";
      //  System.out.println(resultJson);
        return resultJson;
   /*     Collection<CRNode> result = crRepository.graph(10,kks);
        Map<String, Object> kk= toD3Format(result);
       // System.out.println(kk.get("nodes").toString());
       // System.out.println(kk.get("links").toString());
        String resultJson = "{"+kk.get("nodes").toString()+","+kk.get("links").toString()+"}";

       */

    }



}
